﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data;

namespace CCF20Model
{
    public class BaseModel
    {
        protected CCF20Entities ccf20Entities;

        public BaseModel()
        {
            ccf20Entities = new CCF20Entities();
            //ccf20Entities.SavingChanges += new EventHandler(context_SavingChanges);
        }

        private void context_SavingChanges(object sender, EventArgs e)
        {
            // Ensure that we are passed an ObjectContext
            ObjectContext context = sender as ObjectContext;
            if (context != null)
            {

                // Validate the state of each entity in the context
                // before SaveChanges can succeed.
                foreach (ObjectStateEntry entry in
                                    context.ObjectStateManager.GetObjectStateEntries
                                    (
                                        EntityState.Added |
                                        EntityState.Modified
                                    )
                        )
                {
                    // Find an object state entry for a SalesOrderHeader object. 
                    if (!entry.IsRelationship && (entry.Entity.GetType() == typeof(VehicleMaintenanceRecord)))
                    {
                        VehicleMaintenanceRecord vmr = entry.Entity as VehicleMaintenanceRecord;
                        if ((vmr.ServiceMileage == null) && (vmr.ServicePeriod == null))
                        {
                            throw new ArgumentException("里程，周期不可同时为空");
                        }
                    }
                }
            }
        }
    }
}
